package com.tanhua.manager.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlLike;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.manager.enums.StateEnum;
import com.tanhua.manager.exception.BusinessException;
import com.tanhua.manager.mapper.UserInfoMapper;
import com.tanhua.manager.mapper.UserMapper;
import com.tanhua.manager.mapper.UsersFreezeMapper;
import com.tanhua.manager.pojo.*;
import com.tanhua.manager.utils.ManagerThreadLocal;
import com.tanhua.manager.vo.PageResult;
import com.tanhua.manager.vo.UserInformation;
import com.tanhua.manager.vo.UserPageVo;
import com.tanhua.manager.vo.UsersFreezeVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UsersFreezeService {

    private static final String CACHE_KEY_FREEZE_PREFIX = "FREEZE_KEY_";

    @Autowired
    private UsersFreezeMapper usersFreezeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询用户的冻结状态
     *
     * @param id
     * @return
     */
    public String queryState(String id) {
        //设置查询redis的key
        String cacheKey = CACHE_KEY_FREEZE_PREFIX + Long.valueOf(id);
        //根据key去查询redis,判断用户是否被冻结
        String key = redisTemplate.opsForValue().get(cacheKey);
        if (key != null) {
            return key;
        }
        return null;
    }


    /**
     * 查询用户信息
     *
     * @param userID
     * @return
     */
    public UserInformation queryUserInformation(String userID) {
        try {
            //检测当前登录的状态
            Manager manager = ManagerThreadLocal.get();

            //创建返回值对象，即客户详情
            UserInformation userInformation = new UserInformation();
            //到这里就说明验证码通过,该验证用户名和密码了
            QueryWrapper<User> userQuery = new QueryWrapper<>();
            userQuery.eq("id", userID);
            //这个是从数据库中查到的用户对象
            User user = userMapper.selectOne(userQuery);
            QueryWrapper<UserInfo> query = new QueryWrapper<>();
            query.eq("user_id", userID);
            //这个是从数据库中查到的用户对象
            UserInfo userInfo = userInfoMapper.selectOne(query);
            //赋值装车
            userInformation.setMobile(user.getMobile());//手机号
            userInformation.setId(Integer.valueOf(userID));//用户id
            userInformation.setAge(userInfo.getAge());//年龄
            userInformation.setNickname(userInfo.getNickName());//昵称
            userInformation.setLogo(userInfo.getLogo());//头像
            userInformation.setTags(userInfo.getTags());//标签
            userInformation.setSex(userInfo.getSex().toString());//性别
            userInformation.setCity(userInfo.getCity());//注册城市
            userInformation.setIncome(Integer.parseInt(userInfo.getIncome()));//收入
            userInformation.setCreated((int) userInfo.getCreated().getTime());//注册时间
            userInformation.setOccupation(userInfo.getIndustry());//行业

         /*           userInformation.setCountLiked((int) countLiked);喜欢的人数
                       userInformation.setCountBeLiked((int)countBeLiked);粉丝人数*/
            //用户详情表里的能用的都用上了，剩下的去mongodb中拿
            //调用模板查询mongoDB,这个返回的应该是个数，就是当前用户喜欢的人数
            long countLiked = mongoTemplate.count(Query.query(Criteria.where("userId").is(Long.valueOf(userID))), UserLike.class);
            //将条件反转，就是用户的粉丝数
            long countBeLiked = mongoTemplate.count(Query.query(Criteria.where("likeUserId").is(Long.valueOf(userID))), UserLike.class);
            userInformation.setCountLiked((int) countLiked);//
            userInformation.setCountBeLiked((int) countBeLiked);

            //获取最近活跃时间
            //这个是从数据库中查到的用户对象
            UserLocation userLocation = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(Long.valueOf(userID))), UserLocation.class);
            //最近活跃时间
            userInformation.setLastActiveTime(new Long(userLocation.getLastUpdated()).intValue());

            //最近登录地点
            //这个是从数据库中查到的用户对象
            Video video = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(Long.valueOf(userID))), Video.class);
            userInformation.setLastLoginLocation(video.getLocationName());
            //配对人数实在找不到，造假吧
            userInformation.setCountMatching(88);

            //查询并设置用户冻结的状态:1为正常,2为冻结
            String key = this.queryState(userID);
            if (null == key) {
                userInformation.setUserStatus("1");
            } else {
                userInformation.setUserStatus("2");
            }

            userInformation.setPersonalSignature("敲代码累,求包养");

            return userInformation;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 用户数据翻页
     *
     * @param page
     * @param pageSize
     * @param userId
     * @param nickname
     * @param city
     * @return
     */
    public PageResult UserPagesList(Integer page, Integer pageSize, String userId, String nickname, String city) {

        //设置分页参数
        IPage<UserInfo> pageInfo = new Page<>(page, pageSize);
        //构建查询条件
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();

        //如果不为空就进行模糊查询
        if (StringUtils.isNotEmpty(userId)) {
            userInfoQueryWrapper.eq("user_id", userId);
        }
        //如果不为空就进行模糊查询
        if (StringUtils.isNotEmpty(nickname)) {
            userInfoQueryWrapper.like("nick_name", nickname);
        }
        //如果不为空就进行模糊查询
        if (StringUtils.isNotEmpty(city)) {
            userInfoQueryWrapper.like("city", city);
        }

        //查询数据库
        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(pageInfo, userInfoQueryWrapper);
        //获取返回的分页集合对象
        List<UserInfo> userInfoList = userInfoIPage.getRecords();

        //创建返回的PageReultVo对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page); //页码
        pageResult.setCounts((int) userInfoIPage.getTotal()); //总条目数
        pageResult.setPagesize(pageSize); //当前页条目数
        pageResult.setPages((int) userInfoIPage.getPages()); //总页数


        //创建集合存储comment对象
        List<UserPageVo> userPageVoList = new ArrayList<>();

        //因为返回的集合不能不设置，不然前端会报错
        if (CollectionUtils.isEmpty(userInfoList)) {
            pageResult.setItems(userPageVoList);
            return pageResult;
        }

        //遍历对象进行vo封装
        for (UserInfo userInfo : userInfoList) {

            UserPageVo userPageVo = new UserPageVo();
            userPageVo.setId(userInfo.getUserId());

            //头像
            userPageVo.setLogo(userInfo.getLogo());
            //头像状态 ,1通过，2拒绝
            userPageVo.setLogoStatus("1");
            //昵称
            userPageVo.setNickname(userInfo.getNickName());
            //手机号，即用户账号

            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", userInfo.getUserId());
            User user = userMapper.selectOne(userQueryWrapper);

            userPageVo.setMobile(user.getMobile()); //
            //性别 man woman
            userPageVo.setSex(userInfo.getSex().toString());
            //年龄
            userPageVo.setAge(userInfo.getAge());

            //用户状态,1为正常，2为冻结
            //查询并设置用户冻结的状态
            String key = this.queryState(userPageVo.getId().toString());
            if (null == key) {
                userPageVo.setUserStatus("1");
            } else {
                userPageVo.setUserStatus("2");
            }

            //最近活跃时间
            userPageVo.setLastActiveTime(11);
            //城市
            userPageVo.setCity(userInfo.getCity());
            userPageVoList.add(userPageVo);
        }

        pageResult.setItems(userPageVoList);
        return pageResult;
    }


    /**
     * 冻结用户
     *
     * @return
     */
    public Boolean saveFreeze(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {

        UsersFreezeVo usersFreezeVo = new UsersFreezeVo();
        usersFreezeVo.setId(ObjectId.get());
        usersFreezeVo.setUserId(userId.longValue());
        usersFreezeVo.setFreezingTime(freezingTime);
        usersFreezeVo.setFreezingRange(freezingRange);
        usersFreezeVo.setReasonsForFreezing(reasonsForFreezing);
        usersFreezeVo.setFrozenRemarks(frozenRemarks);


        //对获取的用户信息进行非空判断
        if (null == userId) {
            return false;
        }

        //将用户数据转换为数据库的数据
        UsersFreeze usersFreeze = BeanUtil.toBean(usersFreezeVo, UsersFreeze.class);

        usersFreeze.setCreated(new Date(System.currentTimeMillis()));
        usersFreeze.setUpdated(new Date(System.currentTimeMillis()));
        //设置用户冻结状态
        usersFreeze.setFreezingState(StateEnum.FREEZE);

        //将用户信息存入数据库
        usersFreezeMapper.insert(usersFreeze);


        //设置redis中的key
        String cacheKey = CACHE_KEY_FREEZE_PREFIX + userId.toString();
        //设置redis中的value
        Integer cacheValue = usersFreezeVo.getFreezingRange();


        //根据key去查询redis,判断用户是否被冻结
        String key = this.queryState(userId.toString());
        if (null != key) {
            throw new BusinessException("该用户不能重复冻结！");
        }

        //根据前端获取的冻结时间类型,按不同的冻结范围存入redis
        if (usersFreeze.getFreezingTime() == 1) {
            this.redisTemplate.opsForValue().set(cacheKey, String.valueOf(cacheValue), Duration.ofDays(3L));
        } else if (usersFreeze.getFreezingTime() == 2) {
            this.redisTemplate.opsForValue().set(cacheKey, String.valueOf(cacheValue), Duration.ofDays(7L));
        } else if (usersFreeze.getFreezingTime() == 3) {
            this.redisTemplate.opsForValue().set(cacheKey, String.valueOf(cacheValue));
        }

        return true;
    }

    /**
     * 解冻用户
     *
     * @return
     */
    public Boolean unfreeze(Map<String, String> params) {

        try {
            //获取用户id,从redis中根据key删除冻结
            String userId = params.get("userId");
            //根据key去查询redis,判断用户是否被冻结
            String key = this.queryState(userId);
            if (null != key) {
                this.redisTemplate.delete(CACHE_KEY_FREEZE_PREFIX + userId);
            }


            UsersFreeze usersFreeze = new UsersFreeze();

            usersFreeze.setCreated(new Date(System.currentTimeMillis()));
            usersFreeze.setUpdated(new Date(System.currentTimeMillis()));
            //设置用户冻结状态
            usersFreeze.setFreezingState(StateEnum.NORMAL);

            //将解冻原因存入对象,写入到数据库
            usersFreeze.setReasonsForThawing(params.get("reasonsForThawing"));
            this.usersFreezeMapper.insert(usersFreeze);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }


}
